package game;

import java.util.Random;

class Field 
{
    private static int [][] pole;
    private int [] numbers;
    private int n;
    public int xn, yn;
    public Field(int n)
    {
        this.n = n;
        pole = new int[n+2][n+2];
        numbers = new int[n*n-1];
        for(int i = 0; i < n + 2; i++)
        {
            pole[i][0] = -1;
            pole[i][n+1] = -1;
            pole[0][i] = -1;
            pole[n+1][i] = -1;
        }
        for(int i = 0; i < n * n - 1; i++)
        {
            numbers[i] = i + 1;
        }
        xn = n; yn = n;
    }
    
    public void generate()
    {
        for(int j = 0; j < n ; j++)
        {
            for(int i = 0; i < n; i++)
            {
                if(i == n - 1 && j == n - 1)
                    pole[j+1][i+1] = 0;
                else
                    pole[j+1][i+1] = i * n + (j+1);
            }
        }
        int nx = n; int ny = n;
        for(int i = 0; i < 1000; i++)
        {
            Random r = new Random();
            int ic = 0; int jc = 0;
            if(r.nextInt() % 15 > 7)                
                ic = 1;
            else if(r.nextInt() % 17 > 8)
                jc = -1;
            else if(r.nextInt() % 12 > 4)
                ic = -1;
            else
                jc = 1;
            if(nx + ic > 0 && ny + jc > 0 && nx + ic <= n && ny + jc <= n)
            {
                nx += ic;
                ny += jc;
                change(nx, ny);
            }
        }
        xn = nx;
        yn = ny;
    }
    
    public int get(int i, int j)
    {
        return pole[i][j];
    }
    
    public int getN()
    {
        return n;
    }
    
    public void change(int i, int j)
    {
        
        try
        {
            int t = pole[i][j];
            if(t != -1)
            {
                if(pole[i-1][j] == 0)
                {
                    pole[i-1][j] = t;
                    pole[i][j] = 0;
                    xn++;
                }
                else if(pole[i+1][j] == 0)
                {
                    pole[i+1][j] = t;
                    pole[i][j] = 0;
                    xn--;
                }
                else if(pole[i][j-1] == 0)
                {
                    pole[i][j-1] = t;
                    pole[i][j] = 0;
                    yn++;
                }
                else if(pole[i][j+1] == 0)
                {
                    pole[i][j+1] = t;
                    pole[i][j] = 0;
                    yn--;
                }
            }
        }catch(Exception exc)
        {
            
        }
    }
    
    public boolean isSolved()
    {
        boolean result = true;
        for(int j = 1; j < n + 1; j++)
        {
            for(int i = 1; i < n + 1; i++)
            {
                if(pole[j][i] != ((i-1)*n + j)%(n*n))
                {
                    result = false;
                }
            }
        }
        return result;
    }
}
